package com.easylinkin.linkappapi.security.service.impl;

import java.util.Date;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easylinkin.linkappapi.security.entity.LinkappUserLoginInfo;
import com.easylinkin.linkappapi.security.repository.LinkappUserLoginInfoRepository;
import com.easylinkin.linkappapi.security.service.LinkappUserLoginInfoService;

import lombok.extern.slf4j.Slf4j;
import site.morn.boot.data.CrudServiceSupport;


/**
 * 用户登录信息服务实现
 *
 * @author TianGanLin
 * @since 1.0.0, 2019/8/16
 */
@Slf4j
@Service
@Component
@Transactional
public class LinkappUserLoginInfoServiceImpl extends
    CrudServiceSupport<LinkappUserLoginInfo, Long, LinkappUserLoginInfoRepository> implements
    LinkappUserLoginInfoService {

  @Autowired
  private LinkappUserLoginInfoRepository userLoginInfoRepository;

  @Override
  public boolean addErrorCount(Long userId) {
	  LinkappUserLoginInfo userLoginInfo = null;
    Optional<LinkappUserLoginInfo> optional = userLoginInfoRepository.findById(userId);
    if (optional.isPresent()) {
      userLoginInfo = optional.get();
      Date now = new Date();
      Long minute = ((now.getTime() - userLoginInfo.getErrorTime().getTime()) / (1000 * 60));
      if (minute <= 5) {
        if (userLoginInfo.getErrorCount() == 4) {
          userLoginInfo.setLockTime(new Date());
        }
        userLoginInfo.setErrorCount(userLoginInfo.getErrorCount() + 1);
        userLoginInfoRepository.save(userLoginInfo);
        return true;
      } else if (userLoginInfo.getLockTime() == null) {
        userLoginInfo.setErrorCount(1);
        userLoginInfo.setErrorTime(new Date());
        userLoginInfoRepository.save(userLoginInfo);
        return true;
      } else {
        userLoginInfo.setErrorCount(userLoginInfo.getErrorCount() + 1);
        userLoginInfoRepository.save(userLoginInfo);
        return true;
      }
    } else {
      return false;
    }
  }

  @Override
  public void clearErrorCount(Long userId) {
	  LinkappUserLoginInfo userLoginInfo = null;
    Optional<LinkappUserLoginInfo> optional = userLoginInfoRepository.findById(userId);
    if (optional.isPresent()) {
      userLoginInfo = optional.get();
      userLoginInfo.setErrorCount(0);
      userLoginInfoRepository.save(userLoginInfo);
    }
  }

  @Override
  public void clear(Long userId) {
    userLoginInfoRepository.deleteById(userId);
  }

}
